package com.xbongbong.parent.abstracts;

import com.xbongbong.paas.pojo.dto.FormDataDeleteBatchDTO;
import com.xbongbong.paas.pojo.vo.FormDataDeleteBatchVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.parent.interfaces.BusinessDeleteService;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.permission.pojo.dto.VerifyDeletePermissionDTO;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.sys.help.ProPermissionHelp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author 吴峰
 * @date 2022/02/08 15:14
 */
@Component
public abstract class AbstractBusinessDeleteService<F, D> implements BusinessDeleteService<F, D> {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractBusinessDeleteService.class);



    @Override
    public FormDataDeleteBatchVO deleteBatch(FormDataDeleteBatchDTO formDataDeleteBatchDTO) throws XbbException {
        // 校验表单权限
        validatePermission(formDataDeleteBatchDTO);
        // 获取表单
        F form = getForm(formDataDeleteBatchDTO);
        // 校验数据权限
        validateDataPermission(formDataDeleteBatchDTO, form);
        // 删除
        FormDataDeleteBatchVO formDataDeleteBatchVO = deleteBatchNoPermission(formDataDeleteBatchDTO, form);
        // 删除后的逻辑，低代码，业务规则，工作流等
        deleteAfter(formDataDeleteBatchVO.getDeleteIds(), formDataDeleteBatchDTO, form);
        return formDataDeleteBatchVO;
    }



    @Override
    public void validatePermission(FormDataDeleteBatchDTO formDataDeleteBatchDTO) throws XbbException {
        // 经销商业务改businessType
        Integer distributorMark = formDataDeleteBatchDTO.getDistributorMark();
        Integer businessType = formDataDeleteBatchDTO.getBusinessType();
        if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())) {
            businessType = XbbRefTypeEnum.transferBusinessType4Distributor(businessType, distributorMark);
            formDataDeleteBatchDTO.setBusinessType(businessType);
        }
        VerifyDeletePermissionDTO verifyDeletePermissionDTO = new VerifyDeletePermissionDTO();
        BeanUtil.copyProperties(formDataDeleteBatchDTO, verifyDeletePermissionDTO);
        ProPermissionHelp.verifyDeletePermission(verifyDeletePermissionDTO);
        if (formDataDeleteBatchDTO.getDataIdList().size() > 100) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100079.getCode(), SystemErrorCodeEnum.API_ERROR_100079.getMsg(), 100);
        }
    }

    @Override
    public void validateDataPermission(FormDataDeleteBatchDTO formDataDeleteBatchDTO, F form) throws XbbException {
        return;
    }
}
